<template>
  <canvas
    ref="canvas"
    :width="width"
    :height="height"
    @click="clickCanvas"
  ></canvas>
</template>
<script>
export default {
  name: 'VerifyCode',
  props: {
    width: {
      required: true
    },
    height: {
      required: true
    }
  },
  data: () => {
    return {}
  },
  methods: {
    initCanvas () {
      const { width, height } = this
      const canvasWidth = width
      const canvasHeight = height
      const canvas = this.$refs.canvas
      const context = canvas.getContext('2d')
      canvas.height = height // 通过重设高度清空画布
      const sCode =
        'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0'
      const aCode = sCode.split(',')
      const aLength = aCode.length
      let result = ''

      for (let i = 0; i < 4; i++) {
        const j = Math.floor(Math.random() * aLength) // 产生一个随机索引值
        const deg = Math.random() - 0.5 // 产生一个随机弧度
        const txt = aCode[j] // 产生一个随机内容
        result += txt
        const x = 10 + i * 23 // 文字x坐标
        const y = 30 + Math.random() * 8 // 文字y坐标
        context.font = '30px bold'

        context.translate(x, y)
        context.rotate(deg)

        context.fillStyle = randomColor()
        context.fillText(txt, 0, 0)

        context.rotate(-deg)
        context.translate(-x, -y)
      }
      for (let i = 0; i <= 5; i++) {
        // 验证码上显示线条
        context.strokeStyle = randomColor()
        context.beginPath()
        context.moveTo(
          Math.random() * canvasWidth,
          Math.random() * canvasHeight
        )
        context.lineTo(
          Math.random() * canvasWidth,
          Math.random() * canvasHeight
        )
        context.stroke()
      }
      for (let i = 0; i <= 30; i++) {
        // 验证码上显示小点
        context.strokeStyle = randomColor()
        context.beginPath()
        var x = Math.random() * canvasWidth
        var y = Math.random() * canvasHeight
        context.moveTo(x, y)
        context.lineTo(x + 1, y + 1)
        context.stroke()
      }
      this.$emit('checkFn', result.toLowerCase())
    },
    clickCanvas () {
      this.initCanvas()
    }
  },
  mounted () {
    this.initCanvas()
  }
}
// 得到随机的颜色值
function randomColor () {
  var r = Math.floor(Math.random() * 256)
  var g = Math.floor(Math.random() * 256)
  var b = Math.floor(Math.random() * 256)
  return 'rgb(' + r + ',' + g + ',' + b + ')'
}
</script>
